package com.hh.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.usercenter.common.ErrorCode;
import com.hh.usercenter.exception.BussinessException;
import com.hh.usercenter.mapper.UserMapper;
import com.hh.usercenter.model.domain.User;
import com.hh.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hanhui
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-01-12 11:42:51
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";



    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"账号长度过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"密码长度过短");
        }
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9_]+$");
        //userAccount被检测的文本
        Matcher matcher = pattern.matcher(userAccount);
        //匹配上的时候返回true,匹配不通过返回false
        boolean matches = matcher.matches();
        if (!matches) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR);
        }

        //密码和校验码相同
        if (! userPassword.equals(checkPassword)) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR);
        }

        //账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"");
        }


        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BussinessException(ErrorCode.SYSTEM_ERROR);
        }
        return user.getId();
    }

    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"账号长度过短");
        }


        Pattern pattern = Pattern.compile("^[a-zA-Z0-9_]+$");
        //userAccount被检测的文本
        Matcher matcher = pattern.matcher(userAccount);
        //匹配上的时候返回true,匹配不通过返回false
        boolean matches = matcher.matches();
        if (!matches) {
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"密码格式错误！");
        }

        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if(user == null){
            log.info("user login failed,userAccount or userPassword failed");
            throw new BussinessException(ErrorCode.PARAMS_NULL_ERROR,"用户不存在");
        }
        User safetyuser = getSafetyUser(user);
        //记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyuser);
        return safetyuser;
    }

    @Override
    public User getSafetyUser(User OriginUser){
        if(OriginUser == null){
            throw new BussinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        User safetyuser = new User();
        safetyuser.setId(OriginUser.getId());
        safetyuser.setUserName(OriginUser.getUserName());
        safetyuser.setUserAccount(OriginUser.getUserAccount());
        safetyuser.setAvatarUrl(OriginUser.getAvatarUrl());
        safetyuser.setGender(OriginUser.getGender());
//        safetyuser.setUserPassword(OriginUser.getUserPassword());
        safetyuser.setPhone(OriginUser.getPhone());
        safetyuser.setEmail(OriginUser.getEmail());
        safetyuser.setUserStatus(OriginUser.getUserStatus());
        safetyuser.setUserRole(OriginUser.getUserRole());
        safetyuser.setCreateTime(OriginUser.getCreateTime());
        return safetyuser;
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




